package com.kehutong.admin.service;

import com.kehutong.admin.entity.Advert;
import com.kehutong.admin.enums.SourceType;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import java.util.List;

/**
 * @program: kht
 * @description: 广告服务
 * @author: joneron
 * @create: 2021/5/21
 **/
public class AdvertService {

    private static final Logger logger = LoggerFactory.getLogger(AdvertService.class);

    @Inject
    private JdbcSession jdbcSession;

    public Page<Advert> findPage(JSONObject jsonObject) {

        FindPage<Advert> find = jdbcSession.findPage(Advert.class)
                .eq("deleted", false)
                .eq(jsonObject,"status")
                .eq(jsonObject,"positionId")
                .like(jsonObject,"title")
                .like(jsonObject,"endTime")
                .order("createTime", "desc");

        find.page(jsonObject);

        return find.exe();
    }

    public List<Advert> findList(JSONObject jsonObject) {

        String source = jsonObject.getString("source");

        FindArray<Advert> find = jdbcSession.findArray(Advert.class)
                .eq("deleted", false)
                .eq("status",true);

        // 默认获取客户中台相关的广告
        if(Objects.isEmpty(source)){
            find.eq("source", SourceType.MICRO.getId());
        }else{
            find.eq("source", source);
        }

        find.maxEq("endTime",jsonObject.getString("endTime"))
                .order("sortNum","desc");

        return find.exe();
    }

    public Integer save(Advert advert) {
        return jdbcSession.insert(advert);
    }

    public Integer update(Advert advert) {
        return jdbcSession.updateById(advert);
    }

    public Integer delete(String id) {
        Advert result = Pool.get(Advert.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }

    public int saveClickNum(String id) {
        Advert advert = jdbcSession.findById(Advert.class,id);
        if(null != advert){
            advert.setClickNum(advert.getClickNum() + 1);
            return update(advert);
        }
        return 0;
    }
}
